{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alphalens is designed to aid in the analysis of \"alpha factors,\" data transformations that are used to predict future price movements of financial instruments. Alpha factors take the form of a single value for each asset on each day. The dimension of these values is not necessarily important. We evaluate an alpha factor by considering daily factor values relative to one another. \n",
    "\n",
    "It is important to note the difference between an alpha factor and a trading algorithm. A trading algorithm uses an alpha factor, or combination of alpha factors to generate trades.  Trading algorithms cover execution and risk constraints: the business of turning predictions into profits. Alpha factors, on the other hand, are focused soley on making predictions. This difference in scope lends itself to a difference in the methodologies used to evaluate alpha factors and trading algorithms. \n",
    "\n",
    "Alphalens does not contain analyses of things like transaction costs, capacity, or portfolio construction. Those interested in more implementation specific analyses are encouaged to check out [pyfolio](https://github.com/stefan-jansen/pyfolio-reloaded), a library specifically geared towards the evaluation of trading algorithms."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports & Settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:55:32.562984Z",
     "start_time": "2021-09-07T22:55:32.559066Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "source": [
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:55:33.526659Z",
     "start_time": "2021-09-07T22:55:32.742848Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "source": [
    "import pandas as pd\n",
    "import alphalens\n",
    "import seaborn as sns"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:55:33.531635Z",
     "start_time": "2021-09-07T22:55:33.528174Z"
    }
   },
   "source": [
    "%matplotlib inline\n",
    "sns.set_style('white')"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load & Transform Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:55:35.376686Z",
     "start_time": "2021-09-07T22:55:35.359370Z"
    }
   },
   "source": [
    "ticker_sector = {\n",
    "    \"ACN\": 0, \"ATVI\": 0, \"ADBE\": 0, \"AMD\": 0, \"AKAM\": 0, \"ADS\": 0, \"GOOGL\": 0, \"GOOG\": 0,\n",
    "    \"APH\": 0, \"ADI\": 0, \"ANSS\": 0, \"AAPL\": 0, \"AMAT\": 0, \"ADSK\": 0, \"ADP\": 0, \"AVGO\": 0,\n",
    "    \"AMG\": 1, \"AFL\": 1, \"ALL\": 1, \"AXP\": 1, \"AIG\": 1, \"AMP\": 1, \"AON\": 1, \"AJG\": 1, \"AIZ\": 1, \"BAC\": 1,\n",
    "    \"BK\": 1, \"BBT\": 1, \"BRK.B\": 1, \"BLK\": 1, \"HRB\": 1, \"BHF\": 1, \"COF\": 1, \"CBOE\": 1, \"SCHW\": 1, \"CB\": 1,\n",
    "    \"ABT\": 2, \"ABBV\": 2, \"AET\": 2, \"A\": 2, \"ALXN\": 2, \"ALGN\": 2, \"AGN\": 2, \"ABC\": 2, \"AMGN\": 2, \"ANTM\": 2,\n",
    "    \"BCR\": 2, \"BAX\": 2, \"BDX\": 2, \"BIIB\": 2, \"BSX\": 2, \"BMY\": 2, \"CAH\": 2, \"CELG\": 2, \"CNC\": 2, \"CERN\": 2,\n",
    "    \"MMM\": 3, \"AYI\": 3, \"ALK\": 3, \"ALLE\": 3, \"AAL\": 3, \"AME\": 3, \"AOS\": 3, \"ARNC\": 3, \"BA\": 3, \"CHRW\": 3,\n",
    "    \"CAT\": 3, \"CTAS\": 3, \"CSX\": 3, \"CMI\": 3, \"DE\": 3, \"DAL\": 3, \"DOV\": 3, \"ETN\": 3, \"EMR\": 3, \"EFX\": 3,\n",
    "    \"AES\": 4, \"LNT\": 4, \"AEE\": 4, \"AEP\": 4, \"AWK\": 4, \"CNP\": 4, \"CMS\": 4, \"ED\": 4, \"D\": 4, \"DTE\": 4,\n",
    "    \"DUK\": 4, \"EIX\": 4, \"ETR\": 4, \"ES\": 4, \"EXC\": 4, \"FE\": 4, \"NEE\": 4, \"NI\": 4, \"NRG\": 4, \"PCG\": 4,\n",
    "    \"ARE\": 5, \"AMT\": 5, \"AIV\": 5, \"AVB\": 5, \"BXP\": 5, \"CBG\": 5, \"CCI\": 5, \"DLR\": 5, \"DRE\": 5,\n",
    "    \"EQIX\": 5, \"EQR\": 5, \"ESS\": 5, \"EXR\": 5, \"FRT\": 5, \"GGP\": 5, \"HCP\": 5, \"HST\": 5, \"IRM\": 5, \"KIM\": 5,\n",
    "    \"APD\": 6, \"ALB\": 6, \"AVY\": 6, \"BLL\": 6, \"CF\": 6, \"DWDP\": 6, \"EMN\": 6, \"ECL\": 6, \"FMC\": 6, \"FCX\": 6,\n",
    "    \"IP\": 6, \"IFF\": 6, \"LYB\": 6, \"MLM\": 6, \"MON\": 6, \"MOS\": 6, \"NEM\": 6, \"NUE\": 6, \"PKG\": 6, \"PPG\": 6,\n",
    "    \"T\": 7, \"CTL\": 7, \"VZ\": 7,\n",
    "    \"MO\": 8, \"ADM\": 8, \"BF.B\": 8, \"CPB\": 8, \"CHD\": 8, \"CLX\": 8, \"KO\": 8, \"CL\": 8, \"CAG\": 8,\n",
    "    \"STZ\": 8, \"COST\": 8, \"COTY\": 8, \"CVS\": 8, \"DPS\": 8, \"EL\": 8, \"GIS\": 8, \"HSY\": 8, \"HRL\": 8,\n",
    "    \"AAP\": 9, \"AMZN\": 9, \"APTV\": 9, \"AZO\": 9, \"BBY\": 9, \"BWA\": 9, \"KMX\": 9, \"CCL\": 9,\n",
    "    \"APC\": 10, \"ANDV\": 10, \"APA\": 10, \"BHGE\": 10, \"COG\": 10, \"CHK\": 10, \"CVX\": 10, \"XEC\": 10, \"CXO\": 10,\n",
    "    \"COP\": 10, \"DVN\": 10, \"EOG\": 10, \"EQT\": 10, \"XOM\": 10, \"HAL\": 10, \"HP\": 10, \"HES\": 10, \"KMI\": 10\n",
    "}"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "See [yfinance](https://github.com/ranaroussi/yfinance) for details."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:56:03.529624Z",
     "start_time": "2021-09-07T22:55:54.529035Z"
    },
    "scrolled": false
   },
   "source": [
    "import yfinance as yf\n",
    "import pandas_datareader.data as web\n",
    "yf.pdr_override()\n",
    "\n",
    "tickers = list(ticker_sector.keys())\n",
    "df = web.get_data_yahoo(tickers, start='2014-12-01',  end='2017-01-01')\n",
    "df.index = pd.to_datetime(df.index, utc=True)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:56:07.075460Z",
     "start_time": "2021-09-07T22:56:07.028318Z"
    }
   },
   "source": [
    "df = df.stack()\n",
    "df.index.names = ['date', 'asset']\n",
    "df.info()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Compute Factor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For demonstration purposes we will create a predictive factor. To cheat we will look at future prices (5 days into the future) to make sure we'll rank stocks that will perform well high, and vice versa."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:18.301554Z",
     "start_time": "2021-09-07T22:57:18.274493Z"
    }
   },
   "source": [
    "lookahead_bias_days = 5\n",
    "\n",
    "predictive_factor = df.loc[:, 'Open'].unstack('asset')\n",
    "predictive_factor = predictive_factor.pct_change(lookahead_bias_days)\n",
    "# introduce look-ahead bias and make the factor predictive\n",
    "predictive_factor = predictive_factor.shift(-lookahead_bias_days)\n",
    "\n",
    "predictive_factor = predictive_factor.stack()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:20.984032Z",
     "start_time": "2021-09-07T22:57:20.956232Z"
    }
   },
   "source": [
    "predictive_factor.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get pricing info"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pricing data passed to alphalens should contain the entry price for the assets so it must reflect the next available price after a factor value was observed at a given timestamp. Those prices must not be used in the calculation of the factor values for that time. Always double check to ensure you are not introducing lookahead bias to your study.\n",
    "\n",
    "The pricing data must also contain the exit price for the assets, for period 1 the price at the next timestamp will be used, for period 2 the price after 2 timestats will be used and so on.\n",
    "\n",
    "There are no restrinctions/assumptions on the time frequencies a factor should be computed at and neither on the specific time a factor should be traded (trading at the open vs trading at the close vs intraday trading), it is only required that factor and price DataFrames are properly aligned given the rules above.\n",
    "\n",
    "In our example, before the trading starts every day, we observe yesterday factor values. The price we pass to alphalens is the next available price after that factor observation: the daily open price that will be used as assets entry price. Also, we are not adding additional prices so the assets exit price will be the following days open prices (how many days depends on 'periods' argument). The retuns computed by Alphalens will therefore based on  assets open prices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:23.864359Z",
     "start_time": "2021-09-07T22:57:23.820853Z"
    }
   },
   "source": [
    "pricing = df.loc[:, 'Open'].iloc[1:].unstack('asset')\n",
    "pricing.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Often, we'd want to know how our factor looks across various groupings (sectors, industires, countries, etc.), in this example let's use sectors. To generate sector level breakdowns, you'll need to pass alphalens a sector mapping for each traded name. \n",
    "\n",
    "This mapping can come in the form of a MultiIndexed Series (with the same date/symbol index as your factor value) if you want to provide a sector mapping for each symbol on each day. \n",
    "\n",
    "If you'd like to use constant sector mappings, you may pass symbol to sector mappings as a dict.\n",
    "\n",
    "If your sector mappings come in the form of codes (as they do in this tutorial), you may also pass alphalens a dict of sector names to use in place of sector codes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:24.096110Z",
     "start_time": "2021-09-07T22:57:24.089652Z"
    }
   },
   "source": [
    "sector_names = {\n",
    "    0: \"information_technology\",\n",
    "    1: \"financials\",\n",
    "    2: \"health_care\",\n",
    "    3: \"industrials\",\n",
    "    4: \"utilities\",\n",
    "    5: \"real_estate\",\n",
    "    6: \"materials\",\n",
    "    7: \"telecommunication_services\",\n",
    "    8: \"consumer_staples\",\n",
    "    9: \"consumer_discretionary\",\n",
    "    10: \"energy\"\n",
    "}"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Format tearsheet input data\n",
    "\n",
    "Alphalens contains a handy data formatting function to transform your factor and pricing data into the exact inputs expected by the tear sheet functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:28.458028Z",
     "start_time": "2021-09-07T22:57:27.339593Z"
    }
   },
   "source": [
    "factor_data = alphalens.utils.get_clean_factor_and_forward_returns(predictive_factor,\n",
    "                                                                   pricing,\n",
    "                                                                   quantiles=5,\n",
    "                                                                   bins=None,\n",
    "                                                                   groupby=ticker_sector,\n",
    "                                                                   groupby_labels=sector_names)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function inform the user how much data was dropped after formatting the input data. Factor data can be partially dropped due to being flawed itself (e.g. NaNs), not having provided enough price data to compute forward returns for all factor values, or because it is not possible to perform binning. It is possible to control the maximum allowed data loss using 'max_loss' argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:31.580772Z",
     "start_time": "2021-09-07T22:57:31.572685Z"
    }
   },
   "source": [
    "factor_data.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You'll notice that we've placed all of the information we need for our calculations into one dataframe. Variables are the columns, and observations are each row.\n",
    "\n",
    "The integer columns represents the forward returns or the daily price change for the N days after a timestamp. The 1 day forward return for AAPL on 2014-12-2 is the percent change in the AAPL open price on 2014-12-2 and the AAPL open price on 2014-12-3. The 5 day forward return is the percent change from open 2014-12-2 to open 2014-12-9 (5 trading days) divided by 5."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Returns Analysis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Returns analysis gives us a raw description of a factor's value that shows us the power of a factor in real currency values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One of the most basic ways to look at a factor's predictive power is to look at the mean return of different factor quantile. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performance Metrics & Plotting Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:42.454865Z",
     "start_time": "2021-09-07T22:57:36.789777Z"
    }
   },
   "source": [
    "mean_return_by_q_daily, std_err = alphalens.performance.mean_return_by_quantile(\n",
    "    factor_data, by_date=True)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:42.464664Z",
     "start_time": "2021-09-07T22:57:42.456195Z"
    }
   },
   "source": [
    "mean_return_by_q_daily.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:48.167124Z",
     "start_time": "2021-09-07T22:57:42.465893Z"
    }
   },
   "source": [
    "mean_return_by_q, std_err_by_q = alphalens.performance.mean_return_by_quantile(factor_data,\n",
    "                                                                               by_date=False)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:48.174558Z",
     "start_time": "2021-09-07T22:57:48.168421Z"
    }
   },
   "source": [
    "mean_return_by_q.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:57:48.323718Z",
     "start_time": "2021-09-07T22:57:48.175415Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_quantile_returns_bar(mean_return_by_q)\n",
    "sns.despine()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By looking at the mean return by quantile we can get a real look at how well the factor differentiates forward returns across the signal values. Obviously we want securities with a better signal to exhibit higher returns. For a good factor we'd expect to see negative values in the lower quartiles and positive values in the upper quantiles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:58:04.145120Z",
     "start_time": "2021-09-07T22:58:03.864501Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_quantile_returns_violin(mean_return_by_q_daily)\n",
    "sns.despine()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This violin plot is similar to the one before it but shows more information about the underlying data. It gives a better idea about the range of values, the median, and the inter-quartile range. What gives the plots their shape is the application of a probability density of the data at different values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:58:09.077025Z",
     "start_time": "2021-09-07T22:58:09.066574Z"
    }
   },
   "source": [
    "quant_return_spread, std_err_spread = alphalens.performance.compute_mean_returns_spread(mean_return_by_q_daily,\n",
    "                                                                                        upper_quant=5,\n",
    "                                                                                        lower_quant=1,\n",
    "                                                                                        std_err=std_err)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:58:25.353993Z",
     "start_time": "2021-09-07T22:58:24.646403Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_mean_quantile_returns_spread_time_series(\n",
    "    quant_return_spread, std_err_spread);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This rolling forward returns spread graph allows us to look at the raw spread in basis points between the top and bottom quantiles over time. The green line is the returns spread while the orange line is a 1 month average to smooth the data and make it easier to visualize."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:59:49.276665Z",
     "start_time": "2021-09-07T22:59:48.985376Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_cumulative_returns_by_quantile(mean_return_by_q_daily['1D'], period='1D')\n",
    "sns.despine();"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By looking at the cumulative returns by factor quantile we can get an intuition for which quantiles are contributing the most to the factor and at what time. Ideally we would like to see a these curves originate at the same value on the left and spread out like a fan as they move to the right through time, with the higher quantiles on the top."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:00:00.378679Z",
     "start_time": "2021-09-07T23:00:00.013481Z"
    }
   },
   "source": [
    "ls_factor_returns = alphalens.performance.factor_returns(factor_data)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:00:00.385642Z",
     "start_time": "2021-09-07T23:00:00.379812Z"
    }
   },
   "source": [
    "ls_factor_returns.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:00:13.819925Z",
     "start_time": "2021-09-07T23:00:13.593155Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_cumulative_returns(ls_factor_returns['1D'], \n",
    "                                           period='1D')\n",
    "sns.despine();"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While looking at quantiles is important we must also look at the factor returns as a whole. The cumulative factor long/short returns plot lets us view the combined effects overtime of our entire factor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:00:19.360463Z",
     "start_time": "2021-09-07T23:00:18.932347Z"
    }
   },
   "source": [
    "alpha_beta = alphalens.performance.factor_alpha_beta(factor_data)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:00:19.368819Z",
     "start_time": "2021-09-07T23:00:19.361520Z"
    }
   },
   "source": [
    "alpha_beta"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A very important part of factor returns analysis is determing the alpha, and how significant it is. Here we surface the annualized alpha, and beta."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Returns Tear Sheet\n",
    "\n",
    "We can view all returns analysis calculations together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:02:07.820844Z",
     "start_time": "2021-09-07T23:01:54.484579Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.tears.create_returns_tear_sheet(factor_data);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Information Analysis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Information Analysis is a way for us to evaluate the predicitive value of a factor without the confounding effects of transaction costs. The main way we look at this is through the Information Coefficient (IC).\n",
    "\n",
    "From Wikipedia...\n",
    "\n",
    ">The information coefficient (IC) is a measure of the merit of a predicted value. In finance, the information coefficient is used as a performance metric for the predictive skill of a financial analyst. The information coefficient is similar to correlation in that it can be seen to measure the linear relationship between two random variables, e.g. predicted stock returns and the actualized returns. The information coefficient ranges from 0 to 1, with 0 denoting no linear relationship between predictions and actual values (poor forecasting skills) and 1 denoting a perfect linear relationship (good forecasting skills)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performance Metrics & Plotting Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:52.412586Z",
     "start_time": "2021-09-07T22:51:51.282792Z"
    }
   },
   "source": [
    "ic = alphalens.performance.factor_information_coefficient(factor_data)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:52.419393Z",
     "start_time": "2021-09-07T22:51:52.413454Z"
    }
   },
   "source": [
    "ic.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:53.097482Z",
     "start_time": "2021-09-07T22:51:52.420656Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_ic_ts(ic);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By looking at the IC each day we can understand how theoretically predicitive our factor is overtime. We like our mean IC to be high and the standard deviation, or volatility of it, to be low. We want to find consistently predictive factors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:53.539126Z",
     "start_time": "2021-09-07T22:51:53.099859Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_ic_hist(ic);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looking at a histogram of the daily IC values can indicate how the factor behaves most of the time, where the likely IC values will fall, it also allows us to see if the factor has fat tails."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:53.915792Z",
     "start_time": "2021-09-07T22:51:53.540433Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_ic_qq(ic);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These Q-Q plots show the difference in shape between the distribution of IC values and a normal distribution. This is especially helpful in seeing how the most extreme values in the distribution affect the predicitive power."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:55.036877Z",
     "start_time": "2021-09-07T22:51:53.916796Z"
    }
   },
   "source": [
    "mean_monthly_ic = alphalens.performance.mean_information_coefficient(factor_data, \n",
    "                                                                     by_time='M')"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:55.045434Z",
     "start_time": "2021-09-07T22:51:55.037968Z"
    }
   },
   "source": [
    "mean_monthly_ic.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:51:55.653689Z",
     "start_time": "2021-09-07T22:51:55.046721Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_monthly_ic_heatmap(mean_monthly_ic);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By displaying the IC data in heatmap format we can get an idea about the consistency of the factor, and how it behaves during different market regimes/seasons."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Information Tear Sheet\n",
    "\n",
    "We can view all information analysis calculations together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:52:00.646180Z",
     "start_time": "2021-09-07T22:51:55.654706Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.tears.create_information_tear_sheet(factor_data);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Turnover Analysis\n",
    "\n",
    "Turnover Analysis gives us an idea about the nature of a factor's makeup and how it changes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performance Metrics & Plotting Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:03:47.159018Z",
     "start_time": "2021-09-07T23:03:47.152999Z"
    }
   },
   "source": [
    "quantile_factor = factor_data['factor_quantile']\n",
    "turnover_period = 1"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:03:47.822558Z",
     "start_time": "2021-09-07T23:03:47.520393Z"
    }
   },
   "source": [
    "quantiles = range(1, int(quantile_factor.max()) + 1)\n",
    "quantile_turnover = pd.concat([alphalens.performance.quantile_turnover(quantile_factor, q, \n",
    "                                                                       turnover_period)\n",
    "                               for q in quantiles], axis=1)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:03:48.623220Z",
     "start_time": "2021-09-07T23:03:48.606937Z"
    }
   },
   "source": [
    "quantile_turnover.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:52:01.223239Z",
     "start_time": "2021-09-07T22:52:00.961369Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_top_bottom_quantile_turnover(quantile_turnover, \n",
    "                                                     turnover_period);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Factor turnover is important as it indicates the incorporation of new information and the make up of the extremes of a signal. By looking at the new additions to the sets of top and bottom quantiles we can see how much of this factor is getting remade everyday."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:52:01.280601Z",
     "start_time": "2021-09-07T22:52:01.224218Z"
    },
    "scrolled": false
   },
   "source": [
    "factor_autocorrelation = alphalens.performance.factor_rank_autocorrelation(factor_data, \n",
    "                                                                           turnover_period)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:52:01.285016Z",
     "start_time": "2021-09-07T22:52:01.281451Z"
    }
   },
   "source": [
    "factor_autocorrelation.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:52:01.491423Z",
     "start_time": "2021-09-07T22:52:01.286194Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_factor_rank_auto_correlation(factor_autocorrelation);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The autocorrelation of the factor indicates to us the persistence of the signal itself."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Turnover Tear Sheet\n",
    "\n",
    "We can view all turnover calculations together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:52:03.983603Z",
     "start_time": "2021-09-07T22:52:01.492599Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.tears.create_turnover_tear_sheet(factor_data);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Event Style Returns Analysis\n",
    "\n",
    "Looking at the average cumulative return in a window before and after a factor can indicate to us how long the predicative power of a factor lasts. This tear sheet takes a while to run.\n",
    "\n",
    "**NOTE:** This tear sheet takes in an extra argument `pricing`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:05:20.857206Z",
     "start_time": "2021-09-07T23:04:18.318729Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.tears.create_event_returns_tear_sheet(factor_data, \n",
    "                                                pricing, \n",
    "                                                by_group=True);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Groupwise Performance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Many of the plots in Alphalens can be viewed on their own by grouping if grouping information is provided. The returns and information tear sheets can be viewed groupwise by passing in the `by_group=True` argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:05:32.875892Z",
     "start_time": "2021-09-07T23:05:20.858495Z"
    }
   },
   "source": [
    "ic_by_sector = alphalens.performance.mean_information_coefficient(factor_data, \n",
    "                                                                  by_group=True)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:05:32.883105Z",
     "start_time": "2021-09-07T23:05:32.876925Z"
    }
   },
   "source": [
    "ic_by_sector.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:05:40.559285Z",
     "start_time": "2021-09-07T23:05:40.346364Z"
    }
   },
   "source": [
    "alphalens.plotting.plot_ic_by_group(ic_by_sector);"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:05:50.671114Z",
     "start_time": "2021-09-07T23:05:42.861911Z"
    }
   },
   "source": [
    "mean_return_quantile_sector, mean_return_quantile_sector_err = alphalens.performance.mean_return_by_quantile(factor_data, \n",
    "                                                                                                             by_group=True)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:05:50.678723Z",
     "start_time": "2021-09-07T23:05:50.672328Z"
    }
   },
   "source": [
    "mean_return_quantile_sector.head()"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T23:05:51.916170Z",
     "start_time": "2021-09-07T23:05:50.679757Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.plotting.plot_quantile_returns_bar(mean_return_quantile_sector, \n",
    "                                             by_group=True);"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Summary Tear Sheet\n",
    "\n",
    "There are a lot of plots above. If you want a quick snapshot of how the alpha factor performs consider the summary tear sheet."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:53:40.504715Z",
     "start_time": "2021-09-07T22:53:26.595502Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.tears.create_summary_tear_sheet(factor_data)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The Whole Thing\n",
    "\n",
    "If you want to see all of the results create a full tear sheet. By passing in the factor data you can analyze all of the above statistics and plots at once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-09-07T22:54:01.047991Z",
     "start_time": "2021-09-07T22:53:40.505929Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.tears.create_full_tear_sheet(factor_data)"
   ],
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
